package com.wlj.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlj.entity.UserInfo;
import com.wlj.mapper.UserMapper;
import com.wlj.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AccountDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 为什么验证使用这个方法呢
     * 认证管理器配置方法 配置了 auth.userDetailsService(userDetailsService);
     * @EnableWebSecurity
     * public class SecurityConfig extends WebSecurityConfigurerAdapter {
     *
     *     @Autowired
     *     @Qualifier("accountDetailsServiceImpl")
     *     private UserDetailsService userDetailsService;
     *      * 认证管理器配置方法
     *      * @param auth
     *      * @throws Exception
            @Override
             protected void configure(AuthenticationManagerBuilder auth) throws Exception {
             auth.userDetailsService(userDetailsService);
                }
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (s == null || "".equals(s)) {
            throw new RuntimeException("用户不能为空");
        }
        // 调用方法查询用户
        UserInfo sysUser = userMapper.selectOne(
                new QueryWrapper<UserInfo>().lambda().eq(UserInfo::getUsername, s));

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + Constant.PRIORITY_FRONT_USER));

        String encode = passwordEncoder.encode(sysUser.getPassword());
        return new User(sysUser.getUsername(),encode, authorities);
    }
}
